package com.open.capacity.course.service.impl;

import com.open.capacity.common.model.Course;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.course.service.CourseService;
import com.open.capacity.course.dao.CourseDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseDao courseDao;

    @Override
    public PageResult<Course> getSelectCourses(Map<String, Object> params) {
        int count = courseDao.count(params);
        PageUtil.pageParamConver(params,true);
        List<Course> courses = courseDao.getSelectCourses(params);
        return PageResult.<Course>builder().code(0).
                data(courses).count((long) count).build();
    }

    @Override
    public Result addCourse(Course course) {
        boolean isHave = isHaveCourse(course.getTitle(), null);
        if (isHave){
            int result = courseDao.addCourse(course);
            return Result.succeed(result == 1 ? "添加成功" : "添加失败");
        }
        return Result.failed("该课程已存在");
    }

    @Override
    public Result updateCourse(Course course) {
        boolean isHave = isHaveCourse(course.getTitle(),course.getId());
        if (isHave){
            int result = courseDao.updateCourse(course);
            return Result.succeed(result == 1 ? "修改成功" : "修改失败");
        }
        return Result.failed("该课程已存在");
    }

    @Override
    public Result delCourse(int id) {
        int result = courseDao.delCourse(id);
        return Result.succeed(result > 0?"删除成功":"删除失败");
    }

    @Override
    public Result selectCourseById(int id) {
        Course course = courseDao.selectCourseById(id);
        return Result.succeed(course,"");
    }

    // 判断课程是否存在
    private boolean isHaveCourse(String title,Integer id) {
        List<Course> list = courseDao.isHaveCourse(title,id);
        return list.size() == 0?true:false;
    }
}
